<template>
  <div class="root">

    <Banner @boom="$parent.$parent.boom"/>

    <div class="container flex content">
      <div class="left">
        <Carousel :data="carousel"/>
<!--        <Notice/>-->

        <client-only>
          <UserRecommend/>
        </client-only>

        <Posts :topic="topic">
          <template v-slot:header>
            <Category :categorys="category" @post="post()"/>
          </template>
        </Posts>

      </div>
      <div class="right">
        <Right>
          <template v-slot:header>
<!--            <Card>-->
<!--              <slot name="title">-->
<!--                <div class="title" style="position: relative">-->
<!--                  贡献排行榜-->
<!--                  <el-link style="position: absolute;right: 10px">如何上榜？</el-link>-->
<!--                </div>-->
<!--              </slot>-->
<!--            </Card>-->
          </template>
        </Right>
      </div>
    </div>
  </div>
</template>

<script>
import Banner from "../components/Banner";
import Card from "../components/Card";
import Notice from "../components/Notice";
import Posts from "../components/Posts";
import Right from "../components/Right";
import api from "~/utils/api";

export default {
  name: 'IndexPage',
  //指定布局
  layout: 'base',
  transition: 'fade',
  components: {Right, Posts, Notice, Card, Banner},
  //滚动条不跳转到顶部
  scrollToTop:false,
  head() {
    return {
      title: "Simple社区-Simple UI、Simple Pro交流社区",
      meta: [
        {hid: 'description', name: 'description', content: 'Simple社区-Simple UI、Simple Pro交流社区'},
        {name: 'keywords', content: 'SimpleUI、SimplePro、Django Admin主题、Django SimpleUI'},
        {name: 'renderer', content: 'webkit'},
      ]
    }
  },
  data() {
    return {
      topic: [],
      category: [],
      carousel: []
    }
  },
  async asyncData({store, params}) {

    //缓存分类和轮播图

    let topic = [];
    let category = [];
    let carousel = [];
    try {
      let query = {};
      if (params.id) {
        query.pk = params.id;
      }
      if (params.page) {
        query.page = params.page
      }
      topic = await api.getTopic(query);


      //将数据缓存到store，避免重复请求，造成延迟

      //获取轮播图和分类

      if (store.state.carousel.length !== 0) {
        carousel = store.state.carousel
      } else {
        carousel = await api.getCarousel();
        store.commit('setCarousel', carousel);
      }
      //轮播图
      //分类
      if (store.state.category.length !== 0) {
        category = store.state.category
      } else {
        category = await api.getCategory();
        store.commit('setCategory', category);
      }

    } catch (error) {
      console.error(error)
    }
    return {
      topic, category, carousel
    }
  },
  methods: {
    post() {
      //判断是否登录
      if (!this.$store.state.user) {
        //登录
        this.$parent.$parent.showLogin();
        return;
      }

      //如果登录了，就直接跳转到发帖的路由
      this.$router.push({
        name: 'post-topic'
      });
    }
  }
}
</script>
